package org.example.mall.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.mall.entity.User;
import org.example.mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register/phone")
    public ResponseEntity<?> registerByPhone(@RequestParam String phone,
                                             @RequestParam String verificationCode,
                                             @RequestParam String password,
                                             @RequestParam(required = false) String email) {
        try {
            User user = userService.registerByPhone(phone, verificationCode, password, email, null);
            return ResponseEntity.ok(Map.of("success", true, "message", "注册成功", "user", user));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "error", e.getMessage()));
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestParam String username,
                                      @RequestParam String password,
                                      @RequestParam(required = false) String email) {
        try {
            User user = userService.register(username, password, email, null);
            return ResponseEntity.ok(Map.of("success", true, "message", "注册成功", "user", user));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "error", e.getMessage()));
        }
    }

    @PostMapping("/login/phone")
    public ResponseEntity<?> loginByPhone(@RequestParam String phone,
                                          @RequestParam(required = false) String verificationCode,
                                          @RequestParam(required = false) String password,
                                          @RequestParam(required = false) String loginType) {
        try {
            User user;
            if ("password".equals(loginType)) {
                user = userService.loginByPhonePassword(phone, password);
            } else {
                user = userService.loginByPhone(phone, verificationCode);
            }
            
            if (user != null) {
                return ResponseEntity.ok(Map.of("success", true, "message", "登录成功", "user", user));
            }
            return ResponseEntity.badRequest().body(Map.of("success", false, "error", "登录失败"));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "error", e.getMessage()));
        }
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestParam String username,
                                   @RequestParam String password) {
        try {
            User user = userService.login(username, password);
            if (user != null) {
                return ResponseEntity.ok(Map.of("success", true, "message", "登录成功", "user", user));
            }
            return ResponseEntity.badRequest().body(Map.of("success", false, "error", "用户名或密码错误"));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "error", e.getMessage()));
        }
    }

    @PostMapping("/send-code")
    public ResponseEntity<?> sendVerificationCode(@RequestParam String phone) {
        try {
            userService.sendVerificationCode(phone);
            return ResponseEntity.ok(Map.of("success", true, "message", "验证码发送成功"));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "error", e.getMessage()));
        }
    }

    @PutMapping("/{userId}")
    public ResponseEntity<?> updateUserInfo(@PathVariable Long userId,
                                           @RequestBody User userInfo) {
        try {
            User updatedUser = userService.updateUserInfo(userId, userInfo);
            if (updatedUser != null) {
                return ResponseEntity.ok(Map.of("success", true, "message", "用户信息更新成功", "user", updatedUser));
            }
            return ResponseEntity.badRequest().body(Map.of("success", false, "error", "用户不存在"));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "error", e.getMessage()));
        }
    }

    @PutMapping("/{userId}/password")
    public ResponseEntity<?> updatePassword(@PathVariable Long userId,
                                           @RequestParam String oldPassword,
                                           @RequestParam String newPassword) {
        try {
            boolean success = userService.updatePassword(userId, oldPassword, newPassword);
            if (success) {
                return ResponseEntity.ok(Map.of("success", true, "message", "密码更新成功"));
            }
            return ResponseEntity.badRequest().body(Map.of("success", false, "error", "密码更新失败"));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "error", e.getMessage()));
        }
    }

    @GetMapping("/{userId}")
    public ResponseEntity<?> getUserInfo(@PathVariable Long userId) {
        User user = userService.getUserById(userId);
        if (user != null) {
            return ResponseEntity.ok(user);
        }
        return ResponseEntity.notFound().build();
    }
    
    @GetMapping("/check-phone/{phone}")
    public ResponseEntity<Boolean> isPhoneRegistered(@PathVariable String phone) {
        return ResponseEntity.ok(userService.isPhoneRegistered(phone));
    }
}